// Polyfills for Node.js APIs that browserify provided but webpack didn't
globalThis.global = globalThis.global || globalThis;
globalThis.process = globalThis.process || {};
globalThis.Buffer = globalThis.Buffer || require('buffer').Buffer;
process.env = process.env || {};
process.cwd = process.cwd || (() => '/');
globalThis.btoa = globalThis.btoa || (data => Buffer.from(data, 'latin1').toString('base64'));
globalThis.atob = globalThis.atob || (data => Buffer.from(data, 'base64').toString('latin1'));

// crypto.randomBytes() is required by BSON package
// but that throws error in the current browserify replacement for that package.
// Here we create crypto object that will be linked to BSON package
// we provide proper implementation of randomBytes in Kotlin in MongoShellEvaluator
const crypto = require('crypto');
try {
    crypto.randomBytes(1);
} catch (err) {
    crypto.randomBytes = function(size) {
        throw new Error('randomBytes is not implemented');
    };
}

require('../../../../service-provider-core'); // Ensure TextEncoder polyfill is loaded early enough
const ShellApi = require('../../../../shell-api/');
const ShellEvaluator = require('../../../../shell-evaluator/').default;

class ShellInstanceState extends ShellApi.ShellInstanceState {
    constructor(sp, bus, cliOptions) {
        super(sp, bus, cliOptions, require('bson'));
    }
}

/** temporal object that is used to access symbols from closures generated by browserify */
_global = {
    ShellInstanceState,
    ShellEvaluator: ShellEvaluator,
    toShellResult: ShellApi.toShellResult,
    getShellApiType: ShellApi.getShellApiType,
    crypto: crypto
};
